﻿using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.Preferences;
using ApplicationLibrary.SqlConnector;
using Plumber.Accounting.ModuleData;
using Plumber.Accounting.Preferences;
using Plumber.Masters.ModuleData;
using ApplicationLibrary;

namespace Plumber.Accounting.Forms
{
    public partial class JETemplates : ApplicationLibrary.DBManager.DocumentForm
    {
        private ComboBoxManager accountTypesFrom = null;
        //private ComboBoxManager accountTypesTo = null;
        private DRMasterType dRMasterType = null;
        private AccountingPref AccountingPref = null;
        private EnumsManager<TaxRegisterType> eTaxRegister = null;
        private EnumsManager<InvoiceType> eInvoiceType = null;

        public JETemplates()
            : base(Properties.Resources.FN_JETemplates)
        {
            InitializeComponent();
            AccountingPref = new PreferencesManager<AccountingPref>(this.Name, null).ReadPreference();
            if (!AccountingPref.EnableTax)
                tabControl1.TabPages.RemoveByKey(tpgCastleTax.Name);
        }

        #region Virtual Method

        protected override IRadarParameters GetKeyFromDocument()
        {
            return new RadarJETemplatesParam(txtTemplate.Text);
        }

        protected override void OnAttachData()
        {
            dbManager = new dbmanagerJETemplates("JETemplatesForm", new RadarJETemplates(), this);
            dbManager.AddMaster(this, PL_JETemplate.Name, true);
            dbManager.AddSlave(PL_JETemplateDetail.Name, true);
            dbManager.AddRelation("JETemplatesDetail", PL_JETemplate.Template, PL_JETemplateDetail.Template);
            dbManager.AddSlave(PL_JETemplateTaxDetail.Name, true);
            dbManager.AddRelation("JETemplateTaxDetail", PL_JETemplate.Template, PL_JETemplateTaxDetail.Template);

            dRMasterType = new DRMasterType(DRMasterType.Module.All);

            accountTypesFrom = new ComboBoxManager();
            //accountTypesTo = new ComboBoxManager();

            eTaxRegister = new EnumsManager<TaxRegisterType>(cbbTaxRegister);
            eInvoiceType = new EnumsManager<InvoiceType>(cbbDocType);

            RRMasterType rrMasterType = new RRMasterType();
            rrMasterType.Find();
            accountTypesFrom.AddValue<string>(null, "");
            //accountTypesTo.AddValue<string>(null, "");

            for (int t = 0; t < rrMasterType.Count; t++)
            {
                if (rrMasterType.GetValue<MasterTypes>(PL_MasterType.MasterType, t) != MasterTypes.E_Administrator)
                {
                    accountTypesFrom.AddValue(rrMasterType.GetValue<string>(PL_MasterType.Code, t), rrMasterType.GetValue<string>(PL_MasterType.Description, t));
                    //accountTypesTo.AddValue(rrMasterType.GetValue<string>(PL_MasterType.Code, t), rrMasterType.GetValue<string>(PL_MasterType.Description, t));
                }
            }
            accountTypesFrom.AttachTo(jec_Type);

            DRMasterTypeByType dRMasterTypeByType = new DRMasterTypeByType();

            if (dRMasterTypeByType.Find(MasterTypes.E_Condominium))
            {
                string condomType = dRMasterTypeByType.GetValue<string>(PL_MasterType.Code, 0);
                rdrCode.RadarForm = new RadarMasterForm(condomType, RadarMasterForm.Module.All) { DecodeAddress = true };
                rdrCode.AttachCodeType(condomType);
                rdrCode.RadarForm.EnableAddOnFly = true;
                rdrCode.DescriptionControl = txtDescription;
                cbbType.AttachDataReader(new RRMasterTypeForJEPurchase(), true);
            }

            ject_TaxCode.AttachDataReader(new RRTaxCode(), PL_TaxCode.Code, PL_TaxCode.Description);
        }

        protected override void OnBindData()
        {
            BindControl(txtTemplate, PL_JETemplate.Template, NullValue.NotSet);
            BindControl(txtDescription, PL_JETemplate.Description);
            BindControl(cbbTaxRegister, PL_JETemplate.TaxRegister, "SelectedValue");
            BindControl(cbbDocType,     PL_JETemplate.InvoiceType, "SelectedValue");

            BindControl(cbbType, PL_JETemplate.Type, "SelectedValue", NullValue.NotSet, Findable.YES);
            BindControl(rdrCode, PL_JETemplate.Code, Findable.YES);

            dgwJETemplate.AutoGenerateColumns = false;
            dgwJETemplate.DataSource = dbManager.SlaveBinding("JETemplatesDetail");

            BindColumn(jec_Line, PL_JETemplateDetail.Line);
            BindColumn(jec_Type, PL_JETemplateDetail.Type);
            BindColumn(jec_Code, PL_JETemplateDetail.Code);
            BindColumn(jec_DocumentNo, PL_JETemplateDetail.DocumentNo);
            BindColumn(jec_From, PL_JETemplateDetail.From);
            BindColumn(jec_To, PL_JETemplateDetail.To);

            BindColumn(jec_Description, PL_JETemplateDetail.Description);

            dgwJETemplate.AddColumnChangeValue(PL_JETemplateDetail.Type, new ExtendedDataGridView.DataGridViewValueChangeEventHandler(dgwJournalEntries_Type));
            dgwJETemplate.DataGridViewRowEnter += new DataGridViewCellEventHandler(dgwJournalEntries_DataGridViewRowEnter);
            dgwJETemplate.RowIndex = PL_JETemplateDetail.Line;
            BindControl(dgwJETemplate);

            dgwJECastleTax.AutoGenerateColumns = false;
            dgwJECastleTax.DataSource = dbManager.SlaveBinding("JETemplateTaxDetail");

            BindColumn(ject_Line, PL_JETemplateTaxDetail.Line);
            BindColumn(ject_TaxCode, PL_JETemplateTaxDetail.TaxCode);
            BindColumn(ject_Amount, PL_JETemplateTaxDetail.Amount);
            BindColumn(ject_Tax, PL_JETemplateTaxDetail.Tax);
            BindColumn(ject_Total, PL_JETemplateTaxDetail.Total);

            dgwJECastleTax.RowIndex = PL_JETemplateTaxDetail.Line;
            BindControl(dgwJECastleTax);
        }

        protected override bool OnAfterAddNew()
        {
            return base.OnAfterAddNew();
        }

        #endregion

        private void dgwJournalEntries_DataGridViewRowEnter(object sender, DataGridViewCellEventArgs e)
        {
            dgwJournalEntries_Type(sender, e);
            dgwJETemplate[PL_JournalEntryDetail.Description].ReadOnly = string.IsNullOrEmpty(dgwJETemplate.GetValue<string>(e.RowIndex, PL_JournalEntryDetail.Type));
        }

        private void dgwJournalEntries_Type(object sender, DataGridViewCellEventArgs e)
        {
            string typeCode = dgwJETemplate.GetValue<string>(e.RowIndex, PL_JETemplateDetail.Type);
            dgwJETemplate[PL_JETemplateDetail.Code].ReadOnly = string.IsNullOrEmpty(typeCode);
            dgwJETemplate[PL_JETemplateDetail.From].ReadOnly = string.IsNullOrEmpty(typeCode);
            dgwJETemplate[PL_JETemplateDetail.To].ReadOnly = string.IsNullOrEmpty(typeCode);

            if (string.IsNullOrEmpty(typeCode))
                return;

            jec_Code.AttachCodeType(typeCode);

            if (jec_Code.RadarForm != null)
                jec_Code.RadarForm.FilterType = typeCode;
            else
                jec_Code.RadarForm = new RadarMasterForm(typeCode, RadarMasterForm.Module.All);

            if (dRMasterType.Find(typeCode))
                dgwJETemplate[PL_JETemplateDetail.Code].ReadOnly = dRMasterType.GetValue<CodeMode>(PL_MasterType.CodeMode) == CodeMode.E_IsEmpty;
            else
                dgwJETemplate[PL_JETemplateDetail.Code].ReadOnly = false;

            dgwJETemplate[PL_JETemplateDetail.Description].ReadOnly = string.IsNullOrEmpty(dgwJETemplate.GetValue<string>(e.RowIndex, PL_JETemplateDetail.Type));
            dgwJETemplate[PL_JETemplateDetail.DocumentNo].ReadOnly = dRMasterType.GetValue<bool>(PL_MasterType.CanReceiveInvoice);
        }

        private void cbbType_SelectedValueChanged(object sender, System.EventArgs e)
        {
            CodeMode codeMode = CodeMode.E_MustExists;
            if (cbbType.GetValue<string>() == null)
                return;

            if (dRMasterType.Find(cbbType.GetValue<string>()))
            {
                codeMode = dRMasterType.GetValue<CodeMode>(PL_MasterType.CodeMode);
                //masterType = dRMasterType.GetValue<MasterTypes>(PL_MasterType.MasterType);
            }

            if (codeMode == CodeMode.E_IsEmpty)
            {
                rdrCode.Enabled = false;
                rdrCode.DeattachAll();
            }
            else
            {
                rdrCode.ReattachCodeType(cbbType.GetValue<string>());
                rdrCode.Enabled = true;
                rdrCode.RadarForm.FilterType = cbbType.GetValue<string>();
            }
        }
    }

    #region DbManager dbmanagerJETemplates

    /// <summary>
    /// Classe derivata per gestioni particolari
    /// </summary>
    public class dbmanagerJETemplates : DBManager
    {
        public dbmanagerJETemplates(string name, RadarForm radar, DocumentForm document)
            : base(name, radar, document)
        {
            ForeignKey = PL_JETemplate.Template;
        }

        protected override void dAdapter_MasterRowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            base.dAdapter_MasterRowUpdating(sender, e);
        }

        protected override void dAdapter_RowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                if (e.Row.Table.ToString() == PL_JETemplateDetail.Name)
                    e.Row[PL_JETemplateDetail.Template.Name] = GetColumn<string>(PL_JETemplate.Template, Pos);

                if (e.Row.Table.ToString() == PL_JETemplateTaxDetail.Name)
                    e.Row[PL_JETemplateTaxDetail.Template.Name] = GetColumn<string>(PL_JETemplate.Template, Pos);
            }
            base.dAdapter_RowUpdating(sender, e);
        }

        protected override string CreateMasterQuery()
        {
            this.Table = new PL_JETemplate();
            QueryBuilder qB = new QueryBuilder();
            qB.AddSelect();
            qB.AddFrom(this.Table);
            qB.AddCompare(PL_JETemplateDetail.Template, "@p1");

            return qB.Query;
        }

        protected override List<SqlABParameter> CreateMasterParam()
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();

            SqlABParameter sParam = new SqlABParameter("@p1", PL_JETemplate.Template);
            sParam.Value = PL_JETemplate.Template.DefaultValue;
            PList.Add(sParam);
            return PList;
        }

        protected override string CreateSlaveQuery(string name)
        {
            if (name == PL_JETemplateDetail.Name)
            {
                QueryBuilder qB = new QueryBuilder();
                qB.AddSelect();
                qB.AddFrom(PL_JETemplateDetail.Name);
                qB.AddCompare(PL_JETemplateDetail.Template, "@p2");
                qB.AddOrder(PL_JETemplateDetail.Line);
                return qB.Query;
            }

            if (name == PL_JETemplateTaxDetail.Name)
            {
                QueryBuilder qB = new QueryBuilder();
                qB.AddSelect();
                qB.AddFrom(PL_JETemplateTaxDetail.Name);
                qB.AddCompare(PL_JETemplateTaxDetail.Template, "@p3");
                qB.AddOrder(PL_JETemplateTaxDetail.Line);
                return qB.Query;
            }
            return "";
        }

        protected override List<SqlABParameter> CreateSlaveParam(string name)
        {
            if (name == PL_JETemplateDetail.Name)
            {
                List<SqlABParameter> PList = new List<SqlABParameter>();

                SqlABParameter sParam = new SqlABParameter("@p2", PL_JETemplateDetail.Template);
                sParam.Value = "";
                PList.Add(sParam);
                return PList;
            }

            if (name == PL_JETemplateTaxDetail.Name)
            {
                List<SqlABParameter> PList = new List<SqlABParameter>();

                SqlABParameter sParam = new SqlABParameter("@p3", PL_JETemplateDetail.Template);
                sParam.Value = "";
                PList.Add(sParam);
                return PList;
            }
            return null;
        }

        protected override SqlABCommand CreateMasterCommand(ref List<SqlABParameter> dParam)
        {
            return base.CreateMasterCommand(ref dParam);
        }

        protected override void SetParameters(IRadarParameters key, DBCollection collection)
        {
            collection.Parameter[0].Value = key[0];
        }
    }

    #endregion
}